package com.chen.controller;

import com.alibaba.fastjson.JSON;
import com.chen.mapper.UserDao;
import com.chen.pojo.Goods;
import com.chen.pojo.User;
import com.chen.pojo.beans.CommonResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chenchao
 * @date 2023/4/26 15:07
 */
@RequestMapping("/es")
@RestController
@Api(value = "EsController", tags = "ES测试")
@Slf4j
public class EsController {

    @Resource
    private RestHighLevelClient restHighLevelClient;


    @Autowired
    private UserDao userDao;

    //创建索引
    @GetMapping("/createIndex")
    public CommonResult createIndex() throws IOException {
        //创建索引请求
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("personcoder");
        //执行请求，获取响应
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
        log.info("创建es索引======>", createIndexResponse);
        return new CommonResult();
    }

    //查询是否存在索引
    @GetMapping("/existIndex")
    public CommonResult existIndex() throws IOException {
        //查询索引是否存在
        GetIndexRequest personcoder = new GetIndexRequest("personcoder");
        boolean exists = restHighLevelClient.indices().exists(personcoder, RequestOptions.DEFAULT);

        return new CommonResult(exists);
    }

    //删除索引
    @GetMapping("/delIndex")
    public CommonResult delIndex() throws IOException {

        DeleteIndexRequest personcoder = new DeleteIndexRequest("personcoder");
        restHighLevelClient.indices().delete(personcoder, RequestOptions.DEFAULT);
        return new CommonResult();
    }

    @GetMapping("/addDocument")
    public CommonResult addDocument() throws IOException {
        User user = userDao.selectUserByUserName("admin");
        //创建请求
        IndexRequest indexRequest = new IndexRequest("personcoder");
        //设置规则
        indexRequest.id("1");
        indexRequest.timeout("1s");
        indexRequest.source(JSON.toJSON(user), XContentType.JSON);
        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        return new CommonResult(index.status());
    }

    @GetMapping("/updateDocument")
    public CommonResult updateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("personcoder", "1");
        updateRequest.timeout("1s");
        User user = userDao.selectUserByUserName("admin");
        user.setUsername("super");
        updateRequest.doc(JSON.toJSONString(user), XContentType.JSON); //将对象封装丢进去 XContentType方法 将要传输的数据进行告知
        restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return new CommonResult();
    }

    //批量丢入数据
    @GetMapping("/bulkIndexRequest")
    public CommonResult bulkIndexRequest() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        List<User> userList = userDao.findAll();
        for (int i = 0; i < userList.size(); i++) {
            bulkRequest.add(new IndexRequest("personcoder")
                    .source(JSON.toJSONString(userList.get(i)),XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return new CommonResult(bulk.hasFailures());
    }


    //查询
    @GetMapping("/testSearch")
    public CommonResult testSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest("personcoder");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构造搜索的条件
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("username", "admin");
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        Map<String, Object> sourceAsMap=null;
        for (SearchHit hit : search.getHits().getHits()) {
            sourceAsMap = hit.getSourceAsMap();
            log.info("查询======>"+sourceAsMap);
        }
        return new CommonResult(sourceAsMap);
    }


/*    public static void main(String[] args) throws IOException {
      String url="https://search.jd.com/Search?keyword=篮球鞋";
        Document document = Jsoup.parse(new URL(url), 3000);
        Element goodsList = document.getElementById("J_goodsList");
        Elements li = goodsList.getElementsByTag("li");
        ArrayList<Goods> goodList = new ArrayList<>();
        for (Element el : li) {
           String img= el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            System.out.println("https:"+img);
            String price = el.getElementsByClass("p-price").eq(0).text();
            System.out.println(price);
            String title = el.getElementsByClass("p-name p-name-type-2").eq(0).text();
            System.out.println(title);
        }
    }*/


    public static void main(String[] args) throws IOException {
        //全局变量
        FileOutputStream outputStream = null;
//        InputStream inputStream = null;
        for (int i=2;i<6;i++){
            String url="https://pic.netbian.com/4kmeinv/index_"+i+".html";
        Document document = Jsoup.parse(new URL(url), 3000);
        Element element = document.getElementsByClass("slist").get(0);
        Elements li = element.getElementsByTag("li");
        for (Element element1 : li) {
            String src = element1.getElementsByTag("img").eq(0).attr("src");
            String img="https://pic.netbian.com"+src;
            String attr = element1.getElementsByTag("img").eq(0).attr("alt");
            String name=attr.substring(attr.lastIndexOf(" ") + 1);
            URL imgsrcUrl = new URL(img);
            URLConnection urlConnection = imgsrcUrl.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            String outFile = "D:\\Users\\chenchao\\Desktop\\img\\" + name + ".jpg";
            //创建输出流
            outputStream = new FileOutputStream(outFile);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            System.out.println("下载完成");
        }

        }
    }


}
